package com.turman.plyopengl

import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.opengl.GLES20
import android.opengl.GLUtils
import androidx.annotation.DrawableRes
import androidx.annotation.RawRes
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

/**
 * 从文件加载shader
 */
fun Context.readStringFromRaw(@RawRes resId: Int): String {
    return runCatching {
        val builder = StringBuilder()
        val reader = BufferedReader(InputStreamReader(resources.openRawResource(resId)))
        var nextLine: String? = reader.readLine()
        while (nextLine != null) {
            builder.append(nextLine).append("\n")
            nextLine = reader.readLine()
        }
        reader.close()
        builder.toString()
    }.onFailure {
        when (it) {
            is IOException -> {
                throw RuntimeException("Could not open resource: $resId", it)
            }

            is Resources.NotFoundException -> {
                throw RuntimeException("Resource not found: $resId", it)
            }

            else -> {}
        }
    }.getOrThrow()
}

/**
 * 判断是否为debug版本
 */
fun Context.isDebugVersion(): Boolean =
    runCatching {
        (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
    }.getOrDefault(false)

/**
 * 从资源加载贴图
 */
fun Context.loadTexture(@DrawableRes resourceId: Int): Int {
    val textureObjectIds = IntArray(1)
    GLES20.glGenTextures(1, textureObjectIds, 0)
    if (textureObjectIds[0] == 0) {
        LogUtil.w(message = "Could not generate a new OpenGL texture object.")
        return 0
    }

    val option = BitmapFactory.Options().apply {
        inScaled = false
    }
    val bitmap = BitmapFactory.decodeResource(resources, resourceId, option)
    if (bitmap == null) {
        LogUtil.w(message = "Resource ID $resourceId could not be decoded.")
        GLES20.glDeleteTextures(1, textureObjectIds, 0)
        return 0
    }

    //指定设定运用到那个贴图对象
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureObjectIds[0])

    //设置两个过滤器
    GLES20.glTexParameteri(
        GLES20.GL_TEXTURE_2D,
        GLES20.GL_TEXTURE_MIN_FILTER,
        GLES20.GL_LINEAR_MIPMAP_LINEAR
    )
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)

    //将位图数据加载到opengl
    GLUtils.texImage2D(GLES20.GL_TEXTURE_2D,0,bitmap,0)
    //回收位图
    bitmap.recycle()
    //生成MIP映射需要得纹理
    GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D)
    //解除纹理绑定
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0)
    return textureObjectIds[0]
}

fun Context.pxToDp(px: Float): Float {
    return px / resources.displayMetrics.density
}





















